using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.Operations.Commands;

/// <summary>
/// 工序创建命令。
/// </summary>
/// <param name="Operation"></param>
public record CreateOperationCommand(ProcOperationDto Operation) : IRequest<IResult<bool>>;

internal sealed class CreateOperationCommandHandler(IRepository<ProcOperation> repo) : IRequestHandler<CreateOperationCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateOperationCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.LineId == request.Operation.LineId && m.OpCode == request.Operation.OpCode, cancellationToken))
        {
            return Result.Failure("工序编号已存在");
        }

        var operation = request.Operation.Adapt<ProcOperation>();
        var ok = await repo.InsertAsync(operation, cancellationToken);
        return Result.From(ok);
    }
}
